#name, wid, pa
namespace :bld do
  desc "Import scan result to database"
  task :save_history_data => :environment do
    date_now =  Time.now
    pa = ENV['pa'] ? "#{BILI_PRO_PATH}#{ENV['pa']}/" : nil
    id1 = ENV['id1'] || (YAML.load(open(File.join "#{RAILS_ROOT}/config/last.yml")) rescue 0)
    id2 = ENV['id2'] || Scan.last.id
    except_ids = pa ? YAML.load(open(File.join(pa + "except.yml"))) : [-1]
    #=s=p===================================================================
    tudou_and_youku_sp = SpType.find_by_code 'tudou and youku'
    hot_bangumi_sp = SpType.find_by_code 'hot_bangumi'
    hot_bangumi_sp ||= SpType.create! :name => '热门新番特殊记分', :code => 'hot_bangumi'
    #=s=p===================================================================
    puts "reading scan results..."
    data = WeeklyResult.stat(id1, id2, except_ids)
    except_ids = pa ? YAML.load(open(File.join(pa + "except.yml"))) : []
    tmptime = Time.now
    puts "#{tmptime - date_now} seconds passed"
    begin
        puts "importing tmp..."
        WeeklyResultTmp.connection.execute "begin"
        data.each do |r|
          WeeklyResultTmp.connection.execute "insert into weekly_result_tmp
(wid,name,wtype,author,clicks,clicks_rank,comments,comments_rank,stows,stows_rank,danmu,danmu_rank,tj,tj_rank,yb,yb_rank,part,score,score_rank,sp_type_id) values
(#{r.work.wid},'#{r.work.name.gsub /'/, "''"}','#{r.work.ac_type.name}','#{r.work.author_name.gsub /'/, "''"}',#{r.clicks || 'null'},#{r['click_rank'] || 'null'},#{r.comments || 'null'},#{r['comment_rank'] || 'null'},
#{r.stows || 'null'},#{r['stow_rank'] || 'null'},#{r.danmu || 'null'},#{r[:danmu_rank] || 'null'},#{r.tj || 'null'},#{r['tj_rank'] || 'null'},#{r.yb || 'null'},#{r['yb_rank'] || 'null'},
#{r.work.part_count || 'null'},#{r['point'] || 'null'},#{r['point_rank'] || 'null'},#{(r.space_fix < 1 && r.space_fix > 0 ? tudou_and_youku_sp.id : (r[:hot_bangumi] ? hot_bangumi_sp.id : nil)) || 'null'})"
        end
        WeeklyResultTmp.connection.execute "commit"
    puts "#{Time.now - tmptime} seconds passed"
    tmptime = Time.now
      weekly = Weekly.create! :name => ENV['name'], :wid => ENV['wid'], :last => Weekly.latest, :index => ENV['index'] || Weekly.maximum('"index"').to_i + 1
      WeeklyResultWork.transaction do
        puts "updating work..."
        fid = 0
        while true do
          results_tmp = WeeklyResultTmp.all :offset => fid, :limit => 2000, :order => "id"
	        break if results_tmp.empty?
          works = WeeklyResultWork.all :conditions => ["wid in (?)", results_tmp.collect(&:wid)], :order => "id desc"
          puts "get #{fid + 1} to #{fid + 2000}. use #{Time.now - tmptime} sec."
          WeeklyResultTmp.transaction do
            results_tmp.each do |rt|
              wrw = works.detect{|w| w.wid == rt.wid}
              unless wrw && rt.name == wrw.name && rt.wtype == wrw.wtype && rt.author == wrw.author
                wrw = WeeklyResultWork.create :wid => rt.wid, :name => rt.name, :wtype => rt.wtype, :author => rt.author
              end
              rt.update_attribute :weekly_result_work_id, wrw.id
            end
          end
          fid += 2000
        end
      end
    puts "#{Time.now - tmptime} seconds passed"
    tmptime = Time.now
      WeeklyResult.transaction do
        puts "importing..."
        WeeklyResult.connection.execute %[insert into weekly_results (weekly_id,weekly_result_work_id,clicks,clicks_rank,comments,comments_rank,stows,stows_rank,danmu,danmu_rank,tj,tj_rank,yb,yb_rank,part,score,score_rank,sp_type_id )
select #{weekly.id} as weekly_id,weekly_result_work_id,clicks,clicks_rank,comments,comments_rank,stows,stows_rank,danmu,danmu_rank,tj,tj_rank,yb,yb_rank,part,score,score_rank,sp_type_id from weekly_result_tmp]
        puts "#{Time.now - tmptime} seconds passed"
        tmptime = Time.now
        puts "destroy tmp"
        WeeklyResultTmp.connection.execute "delete from weekly_result_tmp"
      end
      puts "#{Time.now - tmptime} seconds passed"
      WeeklyExcept.transaction do
        puts 'excepting...'
        except_ids.each{|wid| WeeklyExcept.create!(:weekly_id => weekly.id, :wid => wid) if wid > 5 && wid != Weekly.latest.wid}
      end
      File.open(%[#{RAILS_ROOT}/config/last.yml],"w"){ |io| YAML.dump id2.to_i,io }
    rescue
      p $!,$@
    end
    puts "#{Time.now - date_now} second complete"
  end
end
